import { LinkOutlined } from '@ant-design/icons';
import { Image, Spin } from 'antd';
import { cardio } from 'ldrs';
import React, { useEffect } from 'react';
import defaultIcon from '../../../public/images/image-default.png';

cardio.register();

export default function Index({ name, icon, port, host, outUrl, innerUrl, disabledLink }) {
  const [loading, setLoading] = React.useState(false);
  const [time, setTime] = React.useState(-1);

  useEffect(() => {
    if (!disabledLink) {
      setLoading(true);
      // const reqList = new ReqList();
      // reqList.push(getTime);
      getTime();
    }
  }, []);

  const getTime = async () => {
    setLoading(true);
    try {
      const res = await window.$axios({
        method: 'get',
        url: '/home-page/speed',
        params: {
          url: getCurrentEnvUrl(),
        },
      });
      setTime(Number(res.data));
      setLoading(false);
    } catch (error) {
      setLoading(false);
      setTime('timeout');
    }
  };

  const getCurrentEnvUrl = () => {
    const currentHost = window.location.host;
    let resUrl = outUrl;
    if (currentHost.includes('192.168')) {
      resUrl = innerUrl;
    }
    return resUrl;
  };

  const handleOpenSite = () => {
    if (disabledLink) {
      return;
    }
    const siteUrl = getCurrentEnvUrl();
    window.open(siteUrl, '_blank');
  };

  return (
    <div className="min-h-[36px] w-full rounded-lg border flex items-center justify-between shadow-md border-text-main/25 dark:border-transparent py-4 px-5 dark:shadow-[0px_0px_20px_0px_#FFFFFF0A,2px_2px_20px_0px_#FFFFFF4D_inset] relative overflow-hidden">
      <div>
        <div className="flex items-center cursor-pointer" onClick={handleOpenSite}>
          <div className="">
            <Image preview={false} src={icon} width={20} fallback={defaultIcon}></Image>
          </div>
          <div className="pl-2 dark:text-text-main-dark/85">{name}</div>
        </div>
        <div className="pt-1 text-xs text-base-content">
          <span className="pr-2">host: {host}</span>
          <span className="pr-2">端口: {Array.isArray(port) ? port.join(',') : port}</span>
        </div>
      </div>

      {!disabledLink && (
        <div className="cursor-pointer pr-2" onClick={handleOpenSite}>
          <LinkOutlined />
        </div>
      )}

      {!disabledLink && (
        <div
          className={`absolute top-0 right-0 text-xs ${
            time === 'timeout' ? 'bg-error' : time < 100 ? 'bg-success' : 'bg-warning'
          } text-white leading-4 px-1 rounded-bl-lg flex items-center justify-center`}
        >
          {loading ? (
            <div className="px-1">
              <Spin indicator={<l-cardio size="18" stroke="1" speed="2" color="white"></l-cardio>} spinning={true} />
            </div>
          ) : (
            <span>{typeof time === 'number' ? `${time}ms` : time}</span>
          )}
        </div>
      )}
    </div>
  );
}
